package controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;

import data.Data;

public class EmailNewsLetterServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		
		try {
			req.getRequestDispatcher("/email_new_letter.jsp").forward(req, resp);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
		throws IOException {

		String title = req.getParameter("title");
		String content = req.getParameter("content");
		String admin = req.getParameter("admin");
		
		if(content!=null&&content.length()>50&&title!=null&&title.length()>10&&admin!=null&&admin.equals("habogay"))
		{
			DBCollection collection = Data.data("email");
			
			DBCursor cursor = collection.find().limit(1);
			while (cursor.hasNext()) {
				DBObject dbObject = (DBObject) cursor.next();

				String email = dbObject.get("email").toString();
				try {
					String mesage = content;
					
		            URL url = new URL("http://yoospain.appspot.com/sendemail");
		            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		            connection.setDoOutput(true);
		            connection.setRequestMethod("POST");
		            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
		            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
		            writer.write("email="+email);
		            writer.write("&name_email="+email);
		            writer.write("&from_email=support1@hatforrent.com");
		            writer.write("&subject="+title);
		            writer.write("&content="+mesage);
		            writer.close();
		    
		            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
		            	 BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
		            }
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
				}
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
}
